package android.app.gfestival;

import java.util.ArrayList;

import android.app.Activity;
import android.app.gfestival.adapter.NewsAdapter;
import android.app.gfestival.rss.RSSFeed;
import android.app.gfestival.rss.RSSItem;
import android.app.gfestival.rss.RssReader;
import android.content.Intent;
import android.db.service.DatabaseService;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class NewsActivity extends Activity{
	private RSSFeed feed;
	private DatabaseService service;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.news);
		service = new DatabaseService(this);
		ListView listView = (ListView) findViewById(R.id.listview_news);
		if(service.isInternetConnected()){
			String urlToRssFeed = "http://www.gfestival.fo/index.php?id=1&type=100";
			feed = RssReader.getFeed(urlToRssFeed );
			if(feed != null){
				NewsAdapter adapter = new NewsAdapter(this, feed.itemlist);
				listView.setAdapter(adapter);
				service.getRssItemDAO().deleteAll();
				try {
					service.getRssItemDAO().insertList(feed.itemlist);
				} catch (Exception e) {
				}
			}
		}else{
			try {
				ArrayList<RSSItem> items = service.getRssItemDAO().findAll();
				NewsAdapter adapter = new NewsAdapter(this, items );
				listView.setAdapter(adapter);
			} catch (Exception e) {
			}
		}
		
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				showBrowser(arg2);
			}
		});
	}

	protected void showBrowser(int position) {
		// TODO Auto-generated method stub
		String url = feed.itemlist.get(position).getLink();
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setData(Uri.parse(url));
		startActivity(i);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		service.onDestroy();
	}
}
